package com.qsl;

import com.google.common.primitives.Bytes;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class GenerateUTF16LEFile {
    public static void main(String[] args) throws Exception {
        // write();
        // read1();
        writePlus();
    }

    private static void write() throws IOException {
        String content = "你好aaa"; // 要写入文件的内容
        OutputStream outputStream = new FileOutputStream("D:/output.txt"); // 输出流，用于写入文件
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-16LE")); // 缓冲写入器，用于将内容转换为UTF-16LE格式并写入文件
        writer.write(content); // 将内容写入文件
        writer.close(); // 关闭缓冲写入器和输出流
    }

    public static void writePlus() throws IOException {
        String colSeparator = "|";
        String END = "\\ud\\ua";
        String rowSeparator = dealStringUnicode(END);
        File file = new File("D:/sample1.txt");
        file.createNewFile();
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        FileChannel channel = raf.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(10240);
        StringBuilder sb = new StringBuilder();
        List<Byte> lineBytes = new ArrayList<>();
        for (int row = 0; row<3; row++) {
            sb.append("abc").append(colSeparator).append("长河").append(colSeparator).append("2023-05-16 14:23:11").append(rowSeparator);
            lineBytes.addAll(Bytes.asList("abc".getBytes("GBK")));
            lineBytes.addAll(Bytes.asList(colSeparator.getBytes("GBK")));
            lineBytes.addAll(Bytes.asList("长河".getBytes("UTF-16LE")));
            lineBytes.addAll(Bytes.asList(colSeparator.getBytes("GBK")));
            lineBytes.addAll(Bytes.asList("2023-05-16 14:23:11".getBytes("GBK")));
            lineBytes.addAll(Bytes.asList(rowSeparator.getBytes("GBK")));
            writeLine(Bytes.toArray(lineBytes), channel, buffer);
            lineBytes.clear();
        }
        buffer.clear();
        channel.close();
        raf.close();
    }

    private static int writeLine(byte[] bytes, FileChannel fc, ByteBuffer buffer) throws IOException {
        ByteBuffer byteBuffer = Optional.ofNullable(buffer).orElse(ByteBuffer.allocate(10240));
        int capacity = byteBuffer.capacity();
        int from = 0;

        int len = capacity;
        while(from < bytes.length) {
            if((len+from) > bytes.length) {
                len = bytes.length - from;
            }
            byteBuffer.clear();
            byteBuffer.put(ByteBuffer.wrap(bytes, from, len));
            byteBuffer.flip();
            fc.write(byteBuffer);
            from += len;
        }
        return from;
    }

    public static String dealStringUnicode(String str) {
        if (isUnicode(str)) {
            return unicodeToString(str);
        }
        return str;
    }

    public static Boolean isUnicode(String str) {
        if (str != null && str.length() > 0) {
            return str.contains("\\u");
        }
        return false;
    }

    public static String unicodeToString(String unicode) {
        if (unicode == null) {
            return null;
        }
        StringBuilder str = new StringBuilder();
        String[] hexs = unicode.split("\\\\u");
        for (String hex : hexs) {
            if (hex != null && hex.length() > 0) {
                str.append((char) Integer.parseInt(hex, 16));
            }
        }
        return str.toString();
    }

    private static void read() throws IOException {
        InputStream inputStream = new FileInputStream("D:/mktdt04.txt.20230505164301"); // 输出流，用于写入文件
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        String line = "";
        while ((line = reader.readLine()) != null) { // 逐行读取文件内容
            System.out.println(line); // 输出当前行的内容
        }
        reader.close();
    }

    private static void read1() throws IOException {
        BufferedInputStream bf = new BufferedInputStream(new FileInputStream("D:/mktdt04.txt.20230505164301"));
        int i;
        byte[] bytes = new byte[10240];
        int size = 0;
        int lines = 0;
        while ((i = bf.read()) != -1) {
            if ((char) i == '\n') {
                // 一行结束
                System.out.println("size = " + size);
                StringBuilder sb = new StringBuilder();
                sb.append(new String(bytes, 0, 24, "GBK"));
                String s = new String(bytes, 24, 60, "UTF-16LE");
                sb.append(new String(s.getBytes("UTF-16LE"), "UTF-16LE"));
                sb.append(new String(bytes, 84, size - 84, "GBK"));
                System.out.println(sb.toString());
                size = 0;
                lines ++;
            }
            if (lines == 2) {
                break;
            }
            bytes[size] = (byte) i;
            size ++;
        }
    }
}
